import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: ttq
 * Date: 13-7-4
 * Time: 下午2:44
 * To change this template use File | Settings | File Templates.
 */
public class LogFilter implements Filter {
    private Log log = LogFactory.getLog(this.getClass());
    private String filterName;

    public void init(FilterConfig config) throws ServletException {
        filterName = config.getFilterName();
        log.info("启动Filter:" + filterName);
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;

        long startTime = System.currentTimeMillis();
        String requestURI = request1.getRequestURI();

        requestURI = request1.getQueryString() == null ? requestURI : (requestURI + "?" + request1.getQueryString());
        chain.doFilter(request1, response1);
        long endTime = System.currentTimeMillis();
        log.info(request1.getRemoteAddr() + "访问了" + requestURI + ",总用时" + (endTime - startTime) + "毫秒。");
    }

    public void destroy() {
        log.info("关闭Filter:" + filterName);
    }
}
